package sourceNsink;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.sql.Timestamp;

public class DataSink implements Runnable{

	
	private volatile boolean running;
	DatagramSocket ds;
	DatagramPacket dp;
	//private final int PORT = 8888;
    File file;
    FileWriter fw;
    PrintWriter pw;
	byte content[] = new byte[33];
	private int teamNr;
	private int stationNr;
	private int rcv_timeout = 4000;
	private boolean socketClosed = false;
	
	public DataSink(int teamNr, int stationNr, int port){
		this.running = true;
		this.teamNr = teamNr;
		this.stationNr = stationNr;
		try {
			ds = new DatagramSocket(port);
			ds.setSoTimeout(rcv_timeout);
			dp = new DatagramPacket(content, content.length);
		} catch (SocketException e) {
			e.printStackTrace();
		}
		
	}
	
	public void run() {	
		//Log erstellen:
		
		System.out.println("Log wird erstellt....");
		Timestamp time = new Timestamp(System.currentTimeMillis());
		String log = "log_" + time;
		String log1 = log.substring(0, 17);
		String log2 = log.substring(18, 20);
		String log3 = log.substring(21, 23);
		log = "Team " + teamNr + "-" + stationNr + "_" + log1 + "h" + log2 + "m" + log3 + "s";
		
		try{											//log erstellen
			file = new File(log + ".txt");
			fw = new FileWriter(file, true);
			pw = new PrintWriter( fw );	
		}catch(IOException e) {
			System.out.println("Logfile nicht erstellt");
			e.printStackTrace();
		}//catch
		System.out.println("DataSink laeuft und nimmt Daten auf!");
		while(running){			//Daten aufnehmen und loggen
			try {
				if(!socketClosed){
					ds.receive(dp);		//Nachricht vom Empf�ngerthread auffangen
				}else{
					ds.close();
				}
			} catch (SocketTimeoutException ste){
				System.out.println("Done!");	//Letzter Schritt f�r Ablauf der Runtime der gesamten Station
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			//System.out.println("DataSink: Hab was");
			long ankunftsZeit = System.currentTimeMillis();
			double zeitlicherSlot = (ankunftsZeit % 1000 / 50.0);
			
			int slot = (int)dp.getData()[24];	//Naechster Sendeslot
			
			if(slot == 21){
				//Eigenes Paket
			}else{

				int stringindx = 0;			//Nachricht herausfiltern
				for(int i = 0; i<24; i++){
					if(dp.getData()[i] == 0){
						stringindx = i;
						break;
					}
				}

				byte messageBytes[] = new byte[24];
				for(int i = 0; i<24; i++){
					messageBytes[i] = dp.getData()[i];
				}
				String content = new String(messageBytes);

				long timestamp = 0;				//Timestamp der Nachricht lesen

				for (int i=0; i<8; i++) {
					timestamp |= ((long)(dp.getData()[25+i])&0xFF) << ((7-i)*8);
				}

				String logNew = "     " + content + "    (  Timestamp: " + timestamp + " Next Slot: " + slot + "  )" + "    at  " + ankunftsZeit + "     on slot " + zeitlicherSlot;


				Timestamp timeNow = new Timestamp(System.currentTimeMillis());
				pw.println(timeNow + logNew);			//log auffuellen
				try{
					fw.flush();	    		
					pw.flush();
				} catch (SocketTimeoutException ste){
					System.out.println("Receive timed out.");
				} catch (IOException e){
					e.printStackTrace();
					System.out.println("Konnte log nicht auffüllen");
				}//catch	
			}
		}
	}

	public void terminate(){
		
		this.socketClosed = true;
		this.running = false;
		System.out.println("DataSink...");
	}	
}
